package util

import (
	"log"
	jwt "github.com/dgrijalva/jwt-go"
	"github.com/go-ini/ini"
)

type Claims struct {
    Id uint
    jwt.StandardClaims
}

var SECRET string
var ADMINSECRET string

func init() {
	cfg, err := ini.Load("config/conf.ini")
	if err != nil {
		log.Println(err)
	}

    SECRET = cfg.Section("jwt").Key("SECRET").String()
	ADMINSECRET = cfg.Section("jwt").Key("ADMINSECRET").String()
}

func MakeCliamsToken(obj Claims) (string, error) {
    token := jwt.NewWithClaims(jwt.SigningMethodHS256, obj)
    tokenString, err := token.SignedString([]byte(SECRET))
    return tokenString, err
}

func ParseCliamsToken(token string) (*Claims, error) {
    tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
        return []byte(SECRET), nil
    })

    if tokenClaims != nil {
        if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
            return claims, nil
        }
    }
    return nil, err
}

func MakeCliamsAdminToken(obj Claims) (string, error) {
    token := jwt.NewWithClaims(jwt.SigningMethodHS256, obj)
    tokenString, err := token.SignedString([]byte(ADMINSECRET))

    return tokenString, err
}

func ParseCliamsAdminToken(token string) (*Claims, error) {
    tokenClaims, err := jwt.ParseWithClaims(token, &Claims{}, func(token *jwt.Token) (interface{}, error) {
        return []byte(ADMINSECRET), nil
    })

    if tokenClaims != nil {
        if claims, ok := tokenClaims.Claims.(*Claims); ok && tokenClaims.Valid {
            return claims, nil
        }
    }

    return nil, err
}